package com.veo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.veo.entity.User;
import com.veo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/adminUser")
public class AdminUserController {

    @Autowired
    private UserService userService;

    /**
     * 去用户管理页面
     * @return
     */
    @RequestMapping("/toUser")
    public String toUser(){
        return "/admin/userManage";
    }

    /**
     * 获取所有的用户信息
     */
    @RequestMapping("/getAllUser")
    @ResponseBody
    public List<User> getAllUser(){
        return userService.list();
    }


    /**
     * 检查用户名是否重复
     * @param username
     * @return
     */
    @RequestMapping("/searchUserName")
    @ResponseBody
    public Map<String,Object> searchUserName(String username){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userService.getOne(wrapper);
        if (user != null){
            map.put("msg","error");
            return map;
        }
        map.put("msg","ok");
        return map;
    }


    /**
     * 用户的修改
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateUser")
    public Map<String, Object>  updateUser(User user){
        boolean flag = userService.updateById(user);
        return returnMsg(flag);
    }

    /**
     * 删除单个用户
     * @param id
     * @return
     */
    @RequestMapping("/deleteUserById")
    @ResponseBody
    public Map<String, Object>  deleteUserById(Integer id){
        boolean flag = userService.removeById(id);
        return returnMsg(flag);
    }

    @RequestMapping("/deleteUserByIds")
    @ResponseBody
    public Map<String, Object>  deleteUserByIds(String ids){
        String[] isids = ids.split(",");
        boolean flag = userService.removeByIds(Arrays.asList(isids));
        return returnMsg(flag);
    }

    private Map<String, Object> returnMsg(boolean flag){
        Map<String,Object> map = new HashMap<>();
        if (flag){
            map.put("msg","ok");
            return map;
        }
        map.put("error","no");
        return map;
    }

}
